package controller

import (
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"go_spider_api/logic"
	"go_spider_api/models"
)

func StartLouPan(c *gin.Context) {

	// 提取spider_name
	spiderName := c.Param("spider_name")
	spiderList := make([]string, len(models.LpSpiderList))

	if spiderName == "all" {
		copy(spiderList, models.LpSpiderList)

	} else {
		// 校验爬虫名字是否正确
		// 检查是否存在对应小区爬虫
		isExists := false

		for _, val := range models.LpSpiderList {
			if val == spiderName {
				isExists = true
				break
			}
		}
		if !isExists {
			zap.L().Error("找不到对应爬虫！")
			c.JSON(200, gin.H{
				"code": 0,
				"msg": "----找不到对应爬虫----",
			})
			return
		}
		spiderList = append(spiderList, spiderName)
	}
	//fmt.Println(spiderList)

	err := logic.StartLouPan(spiderList)

	if err != nil {
		zap.L().Error("启动楼盘爬虫失败，err:", zap.Error(err))
		c.JSON(200, gin.H{
			"code": 0,
			"msg": "----启动楼盘爬虫失败！----",
		})
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg": "----成功启动对应楼盘爬虫----",
	})
}

func KillLouPan(c *gin.Context) {
	// 参数为空，默认杀死全部
	spiderName := c.Param("spider_name")
	if spiderName == "all" {
		spiderList := make([]string, len(models.LpSpiderList))
		copy(spiderList, models.LpSpiderList)
		err := logic.KillEsfZf(spiderList)
		if err != nil {
			c.JSON(200, gin.H{
				"code": 0,
				"msg": "----爬虫服务KILL失败----",
			})
			return

		}

	}
	if spiderName != "" {

		err := logic.KillEsfZf([]string{spiderName})
		if err != nil {
			c.JSON(200, gin.H{
				"code": 0,
				"msg": "----爬虫服务KILL失败----",
			})
			return

		}

	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg": "----成功杀死对应楼盘爬虫----",
	})
}
